using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace SearchEngineTextExtractor
{
    public partial class MainForm : Form
    {
        private TextBox txtKeyword;
        private TextBox txtBaiduResult;
        private TextBox txtBingResult;
        private Button btnSearch;
        private Label lblStatus;
        public MainForm()
        {
            InitializeForm();
        }
        private void InitializeForm()
        {
            // 窗体设置
            this.Text = "搜索引擎文字提取工具 ";
            this.Size = new System.Drawing.Size(850, 650);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 搜索框
            txtKeyword = new TextBox
            {
                Location = new System.Drawing.Point(120, 20),
                Size = new System.Drawing.Size(500, 25),
                Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
            };
            btnSearch = new Button
            {
                Text = "开始搜索",
                Location = new System.Drawing.Point(630, 20),
                Size = new System.Drawing.Size(100, 25),
                Anchor = AnchorStyles.Top | AnchorStyles.Right
            };
            btnSearch.Click += (sender, e) => StartSearch();
            // 百度结果框
            txtBaiduResult = new TextBox
            {
                Multiline = true,
                ScrollBars = ScrollBars.Vertical,
                Location = new System.Drawing.Point(20, 60),
                Size = new System.Drawing.Size(380, 520),
                ReadOnly = true,
                WordWrap = true,
                Font = new System.Drawing.Font("Microsoft YaHei", 10)
            };
            // 必应结果框
            txtBingResult = new TextBox
            {
                Multiline = true,
                ScrollBars = ScrollBars.Vertical,
                Location = new System.Drawing.Point(420, 60),
                Size = new System.Drawing.Size(380, 520),
                ReadOnly = true,
                WordWrap = true,
                Font = new System.Drawing.Font("Microsoft YaHei", 10)
            };
            lblStatus = new Label
            {
                Location = new System.Drawing.Point(20, 590),
                Size = new System.Drawing.Size(800, 20),
                Text = "准备就绪"
            };

            this.Controls.Add(new Label { Text = "搜索关键字:", Location = new System.Drawing.Point(20, 22) });
            this.Controls.Add(txtKeyword);
            this.Controls.Add(btnSearch);
            this.Controls.Add(txtBaiduResult);
            this.Controls.Add(txtBingResult);
            this.Controls.Add(lblStatus);
        }

        private void StartSearch()
        {
            string keyword = txtKeyword.Text.Trim();
            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入搜索关键字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 清空结果
            txtBaiduResult.Clear();
            txtBingResult.Clear();
            lblStatus.Text = "正在搜索...";
            btnSearch.Enabled = false;
            ThreadPool.QueueUserWorkItem(state => SearchBaidu(keyword));
            ThreadPool.QueueUserWorkItem(state => SearchBing(keyword));
        }

        private void SearchBaidu(string keyword)
        {
            try
            {
                string url = $"https://www.baidu.com/s?wd={Uri.EscapeDataString(keyword)}";
                string html = DownloadHtml(url);
                string text = ExtractTextFromHtml(html);
                string result = TruncateText(text, 200);

                this.Invoke((MethodInvoker)delegate {
                    txtBaiduResult.Text = result;
                    UpdateStatus();
                });
            }
            catch (Exception ex)
            {
                this.Invoke((MethodInvoker)delegate {
                    txtBaiduResult.Text = $"百度搜索失败: {ex.Message}";
                    UpdateStatus();
                });
            }
        }

        private void SearchBing(string keyword)
        {
            try
            {
                string url = $"https://www.bing.com/search?q={Uri.EscapeDataString(keyword)}";
                string html = DownloadHtml(url);
                string text = ExtractTextFromHtml(html);
                string result = TruncateText(text, 200);

                this.Invoke((MethodInvoker)delegate {
                    txtBingResult.Text = result;
                    UpdateStatus();
                });
            }
            catch (Exception ex)
            {
                this.Invoke((MethodInvoker)delegate {
                    txtBingResult.Text = $"必应搜索失败: {ex.Message}";
                    UpdateStatus();
                });
            }
        }

        private string DownloadHtml(string url)
        {
            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
                return client.DownloadString(url);
            }
        }

        private string ExtractTextFromHtml(string html)
        {
            string noScript = Regex.Replace(html, @"<script[^>]*>[\s\S]*?</script>", " ", RegexOptions.IgnoreCase);
            noScript = Regex.Replace(noScript, @"<style[^>]*>[\s\S]*?</style>", " ", RegexOptions.IgnoreCase);
            string noTags = Regex.Replace(noScript, "<[^>]+>", " ");
            string decoded = WebUtility.HtmlDecode(noTags);
            string singleSpaced = Regex.Replace(decoded, @"\s+", " ");
            return singleSpaced.Trim();
        }

        private string TruncateText(string text, int length)
        {
            if (string.IsNullOrEmpty(text) || text.Length <= length)
                return text;
            int pos = length;
            while (pos > 0 && IsChineseChar(text[pos]))
                pos--;

            return text.Substring(0, pos > 0 ? pos : length) + $"...(共{text.Length}字)";
        }

        private bool IsChineseChar(char c)
        {
            return c >= 0x4E00 && c <= 0x9FA5;
        }
        private void UpdateStatus()
        {
            if (txtBaiduResult.Text.Length > 0 && txtBingResult.Text.Length > 0)
            {
                lblStatus.Text = "搜索完成 - " + DateTime.Now.ToString("HH:mm:ss");
                btnSearch.Enabled = true;
            }
        }
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}